﻿using System;
using System.Net;
using System.Windows;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Linq;
using System.Text;


public class JSonner
{
		public T DeserializeJsonToType<T>(string jsonString)
		{
				if (string.IsNullOrEmpty(jsonString)) return default(T);

				try
				{
						using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
						{
								DataContractJsonSerializer serializer =
																	new DataContractJsonSerializer(typeof(T)); //may be list: typeof( List<Person> )
								return (T)serializer.ReadObject(ms);
						}
				}
				catch (Exception ex)
				{
						return default(T);
				}
		}//fM  

		public string SerializeToJsonString(object pObjectToSerialize)
		{
				using (MemoryStream ms = new MemoryStream())
				{
						DataContractJsonSerializer serializer =
													new DataContractJsonSerializer(pObjectToSerialize.GetType());
		
						serializer.WriteObject(ms, pObjectToSerialize);
						ms.Position = 0;
						using (StreamReader reader = new StreamReader(ms))
						{ return reader.ReadToEnd(); }
				}
		}   //fM 

		public string SerializeToXml(object pObjectToSerialize)
		{
				using (MemoryStream ms = new MemoryStream())
				{
						DataContractSerializer serializer = new DataContractSerializer(pObjectToSerialize.GetType());
						serializer.WriteObject(ms, pObjectToSerialize);
						ms.Position = 0;
						using (StreamReader reader = new StreamReader(ms))
						{ return reader.ReadToEnd(); }
				}


		}//fM

		public T DeserializeFromXml<T>(string xmlString)
		{
				if (string.IsNullOrEmpty(xmlString)) return default(T);

				try
				{
						using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(xmlString)))
						{
								DataContractSerializer serializer =
																	new DataContractSerializer(typeof(T)); //may be list: typeof( List<Person> )
								return (T)serializer.ReadObject(ms);
						}
				}
				catch (Exception ex)
				{
						return default(T);
				}
		}//fM  


}//fM

